package com.videomeetting.legend.videomeetting.activity.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.videomeetting.legend.videomeetting.R;
import com.videomeetting.legend.videomeetting.activity.utils.EthernetInfo;
import com.videomeetting.legend.videomeetting.activity.utils.MyUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import static android.Manifest.permission.INTERNET;


/**
 * Created by legend on 18-6-29.
 */

public class SettingFragment extends Fragment {
    private WifiManager my_wifiManager;
    private DhcpInfo dhcpInfo;
    private DhcpInfo ethdhcpInfo;
    public String ipAddress = null;
    public String maskAddress = null;
    public String gatewayAddress = null;
    public String dns1Address = null;
    public String dns2Address = null;
    WifiInfo connectionInfo;
    //    NetworkInterface
    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        // 获取以太网连接状态(DHCP IP)
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
//        EthernetDevInfo mEthInfo =mEthManager.getSavedEthConfig();
        EthernetInfo ethernetInfo = new EthernetInfo();
//        ethernetInfo.getInfo(connectivityManager);
//         ethdhcpInfo = ;
        ethernetInfo.getLocalIpAddress();
        ipAddress =ethernetInfo.ipAddress;
        maskAddress  = ethernetInfo.maskAddress;
        gatewayAddress = ethernetInfo.getLocalDNS();
        dns1Address =ethernetInfo.getLocalDNS();
//        int ethernetConnectState = ethernetManager.getEthernetConnectState();
//        IpConfiguration.IpAssignment ipAssignment = configuration.getIpAssignment();
//        IpConfiguration configuration = (IpConfiguration) ethernetConnectState;
//        configuration.ipAssignment
//        EthernetDevInfo mEthernetDevInfo = configuration;
//        String etho_mode = mEthernetDevInfo.getConnectMode();  //得到连接模式  手动  DHCP
//        String IpAddress = mEthernetDevInfo.getIpAddress();  //得到ip地址
//        String NetMask = mEthernetDevInfo.getNetMask();  //得到掩码
//        String DNS = mEthernetDevInfo.getDnsAddr();  //得到DNS
//        String GateWay = mEthernetDevInfo.getRouteAddr();  //得到网关
//      Toast.makeText(this, etho_mode + IpAddress + NetMask + DNS + GateWay, Toast.LENGTH_LONG).show();
//        if(etho_mode.equals("manual")){
//            Log.i(TAG, "manual");
//        }else if(etho_mode.equals("dhcp")){
//            Log.i(TAG, "dhcp");
//            Toast.makeText(this, etho_mode + IpAddress + NetMask + DNS + GateWay, Toast.LENGTH_LONG).show();
//        }



//        Log.i("legend", "onCreate: ipAddress: " +ipAddress);
//        Log.i("legend", "onCreate: ipAddress: " +ipAddress);
        my_wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        dhcpInfo =my_wifiManager.getDhcpInfo();

        connectionInfo = my_wifiManager.getConnectionInfo();
//        int ipAddress = connectionInfo.getIpAddress();
//        connectionInfo.get
        Log.i("legend", "onCreate: wifi ip: " + dhcpInfo.ipAddress);
        Log.i("legend", "onCreate: wifi mask: " + dhcpInfo.netmask);
        Log.i("legend", "onCreate: wifi gateway: " + dhcpInfo.gateway);
        Log.i("legend", "onCreate: wifi dns: " + dhcpInfo.dns1);
    }
    private boolean isUsingStaticIp() {
        return Settings.System.getInt(getActivity().getContentResolver(),
                "ethernet_use_static_ip", 0) == 1 ? true : false;
    }
    /**
     * 获取IP地址 ipv4 ipv6
     */
    @RequiresPermission(INTERNET)
    public static String getIPAddress(final boolean useIPv4) {
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                // To prevent phone of xiaomi return "10.0.2.15"
                if (!ni.isUp()) continue;
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String hostAddress = inetAddress.getHostAddress();
                        boolean isIPv4 = hostAddress.indexOf(':') < 0;
                        if (useIPv4) {
                            if (isIPv4) return hostAddress;
                        } else {
                            if (!isIPv4) {
                                int index = hostAddress.indexOf('%');
                                return index < 0
                                        ? hostAddress.toUpperCase()
                                        : hostAddress.substring(0, index).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

        @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.i("legend", "onCreate: ipAddress: " +ipAddress);
        Log.i("legend", "onCreate: maskAddress: " +maskAddress);
        Log.i("legend", "onCreate: gatewayAddress: " +gatewayAddress);
        Log.i("legend", "onCreate: dns1Address: " +dns1Address);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_setting, container, false);
        Button speedTestBtn = (Button) view.findViewById(R.id.fragment_setting_speed_test_btn);
        EditText ip = (EditText) view.findViewById(R.id.fragment_setting_local_ip_et);
        EditText mask = (EditText) view.findViewById(R.id.fragment_setting_local_mask_et);
        EditText getway = (EditText) view.findViewById(R.id.fragment_setting_local_getway_et);
        EditText dns = (EditText) view.findViewById(R.id.fragment_setting_local_dns_et);
//        String ipString = intToIp(dhcpInfo.ipAddress);
        boolean wifiConnection = MyUtils.hasWifiConnection(getContext());
        if (!wifiConnection) {
            ip.setText(ipAddress);
        }else {
            ip.setText(intToIp(dhcpInfo.ipAddress));
        }
//        String maskString = intToIp(dhcpInfo.netmask);
        if (!wifiConnection) {
            mask.setText(maskAddress);
        }
        else {
            mask.setText("255.255.255.0");
        }
//        String getwayString = intToIp(dhcpInfo.gateway);
        if (!wifiConnection) {
            getway.setText(gatewayAddress);
        }else {
            getway.setText(intToIp(dhcpInfo.gateway));
        }
//        String dns1 = intToIp(dhcpInfo.dns1);
//        String dns2 = intToIp(dhcpInfo.dns2);
        if (!wifiConnection) {
            dns.setText(dns1Address);
        }else {
            dns.setText(intToIp(dhcpInfo.dns1));
        }

        speedTestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpeedTestFragment speedTestFragment = new SpeedTestFragment();
                speedTestFragment.show(getChildFragmentManager(), "sss");
            }
        });
        return view;
    }

    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + ((paramInt >> 8 & 0xFF)) + "." + ((paramInt >> 16 & 0xFF)) + "."
                + ((paramInt >> 24 & 0xFF));
    }


    /**
     * Convert a IPv4 address from an integer to an InetAddress.
     *
     * @param hostAddress an int corresponding to the IPv4 address in network byte order
     */
    public static InetAddress intToInetAddress(int hostAddress) {
        byte[] addressBytes = {(byte) (0xff & hostAddress),
                (byte) (0xff & (hostAddress >> 8)),
                (byte) (0xff & (hostAddress >> 16)),
                (byte) (0xff & (hostAddress >> 24))};

        try {
            return InetAddress.getByAddress(addressBytes);
        } catch (UnknownHostException e) {
            throw new AssertionError();
        }
    }

}
